package com.lg.jvm;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * 自定义类加载器 打破双亲委派模型
 *
 * @author Gang.Li
 * @date 2021/6/3 15:24
 */
public class MyClassLoaderTest1 {
    static class MyClassLoader extends ClassLoader {

        /**
         * 定义自定义类加载器加载的路径
         */
        private String classPath;

        public MyClassLoader(String classPath) {
            this.classPath = classPath;
        }

        private byte[] loadByte(String name) throws Exception {
            name = name.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        /**
         * 重写类加载方法，实现自己的加载逻辑，不委派给双亲加载
         *
         * @param name
         * @param resolve
         * @return
         * @throws ClassNotFoundException
         */
        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                // 查看该类是否已经被加载过了
                Class<?> c = findLoadedClass(name);

                if (c == null) {
                    long start = System.nanoTime();
                    // 防止加载类是 需要加载Object 这种必须加载的核心类，还是需要对类的加载进行筛选
                    //非自定义的类还是走双亲委派加载
                    if (!name.startsWith("com.lg.jvm")) {
                        c = this.getParent().loadClass(name);
                    } else {
                        c = findClass(name);
                    }
                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(start);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                final byte[] bytes = loadByte(name);
                return defineClass(name, bytes, 0, bytes.length);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ClassNotFoundException();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        //初始化自定义类加载器，会先初始化父类ClassLoader，其中会把自定义类加载器的父加载器设置为应用程序类加载器AppClassLoader
        //MyClassLoader classLoader = new MyClassLoader("E:/idea_workspace/wheel/data");
        ////D盘创建 test/com/tuling/jvm 几级目录，将User类的复制类User1.class丢入该目录
        //Class clazz = classLoader.loadClass("java.lang.String");
        //Object obj = clazz.newInstance();
        //Method method = clazz.getDeclaredMethod("print", null);
        //method.invoke(obj, null);
        //System.out.println(clazz.getClassLoader().getClass().getName());

        MyClassLoader classLoader = new MyClassLoader("E:/idea_workspace/wheel/data");
        //D盘创建 test/com/tuling/jvm 几级目录，将User类的复制类User1.class丢入该目录
        Class clazz = classLoader.loadClass("com.lg.jvm.User1");
        Object obj = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("sout", null);
        method.invoke(obj, null);
        System.out.println(clazz.getClassLoader().getClass().getName());

        MyClassLoader classLoader2 = new MyClassLoader("E:/idea_workspace/wheel/data");
        //D盘创建 test/com/tuling/jvm 几级目录，将User类的复制类User1.class丢入该目录
        Class clazz2 = classLoader2.loadClass("com.lg.jvm.User1");
        Object obj2 = clazz2.newInstance();
        Method method2 = clazz2.getDeclaredMethod("sout", null);
        method2.invoke(obj2, null);
        System.out.println(clazz.getClassLoader().getClass().getName());

        /*当前加载器我的类加载器为：com.lg.jvm.MyClassLoaderTest1$MyClassLoader@28d93b30
        我被自定义加载器加载啦
        com.lg.jvm.MyClassLoaderTest1$MyClassLoader
        当前加载器我的类加载器为：com.lg.jvm.MyClassLoaderTest1$MyClassLoader@74a14482
        我被自定义加载器加载啦
        com.lg.jvm.MyClassLoaderTest1$MyClassLoader*/
    }
}
